package com.bsoft.gol.editor.dao;


import com.bsoft.gol.editor.editor.EditorQuestionnaire;
import com.bsoft.gol.editor.editor.qo.EditorQuestionnaireQo;
import com.bsoft.gol.editor.utils.CommonUtils;
import ctd.persistence.annotation.DAOMethod;
import ctd.persistence.annotation.DAOParam;
import ctd.persistence.support.hibernate.template.AbstractHibernateStatelessResultAction;
import ctd.persistence.support.hibernate.template.HibernateSessionTemplate;
import ctd.persistence.support.hibernate.template.HibernateStatelessResultAction;
import ctd.util.converter.ConversionUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.StatelessSession;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.transform.Transformers;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Sangs on 2020/4/3.
 */
public abstract class EditorQuestionnaireDAO extends ctd.persistence.support.hibernate.HibernateSupportDelegateDAO<EditorQuestionnaire> {

    public EditorQuestionnaireDAO() {
        this.setKeyField("questionnaireId");
    }

    @DAOMethod(sql = " from  EditorQuestionnaire where questionnaireCode=:questionnaireCode  order by questionnaireVersion desc")
    public abstract List<EditorQuestionnaire> queryEditorQuestionnaireCodeList(@DAOParam("questionnaireCode") String questionnaireCode);


    @DAOMethod(sql = "update EditorQuestionnaire set deleteFlag=1 where questionnaireId =:questionnaireId ")
    public abstract void updateEditorQuestionnaireFlag(@DAOParam("questionnaireId") String questionnaireId);

    @DAOMethod(sql = "update EditorQuestionnaire set type =:type where questionnaireId =:questionnaireId ")
    public abstract void updateEditorQuestionnaireType(@DAOParam("questionnaireId") String questionnaireId, @DAOParam("type") String type);


    @DAOMethod(sql = "update EditorQuestionnaire set deleteFlag=1 where questionnaireId not in (select questionnaireId from EditorQuestionnaireTitle) ")
    public abstract void updateEditorQuestionnaireFlags();


    /**
     * 查询列表
     *
     * @return
     */
    public List<EditorQuestionnaire> queryEditorQuestionnaireList(final EditorQuestionnaireQo req) {
        HibernateStatelessResultAction<List<EditorQuestionnaire>> action = new AbstractHibernateStatelessResultAction<List<EditorQuestionnaire>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                String sql = createEditorQuestionnaireListSql(req);
                SQLQuery sqlQuery = ss.createSQLQuery(sql);
                if (CommonUtils.isNotNull(req.getQuestionnaireName())) {
                    sqlQuery.setParameter("questionnaireName","%"+req.getQuestionnaireName()+"%");
                }
                if (CommonUtils.isNotNull(req.getQuestionnaireMould())) {
                    sqlQuery.setParameter("questionnaireMould","%"+req.getQuestionnaireMould()+"%");
                }
                if (CommonUtils.isNotNull(req.getQuestionnaireState())) {
                    sqlQuery.setParameter("questionnaireState",req.getQuestionnaireState());
                }
                if (CommonUtils.isNotNull(req.getQuestionnaireIdList())) {
                    sqlQuery.setParameterList("questionnaireIdList", req.getQuestionnaireIdList());
                }
                sqlQuery = (SQLQuery) sqlQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);

                sqlQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
                //分页
                if (CommonUtils.isNotEmpty(req.getPageNo()) && CommonUtils.isNotEmpty(req.getPageSize())) {
                    int first = req.getPageNo() > 0 ? (req.getPageNo() - 1) * req.getPageSize() : 0;
                    sqlQuery.setFirstResult(first);
                    sqlQuery.setMaxResults(req.getPageSize());
                }
                List<Map> list = sqlQuery.list();
                List<EditorQuestionnaire> voList = new ArrayList<>();
                if (CommonUtils.isNotEmpty(list)) {
                    for (Map map : list) {
                        voList.add(ConversionUtils.convert(map, EditorQuestionnaire.class));
                    }
                } else {
                    voList = new ArrayList<>();
                }
                setResult(voList);

            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    private String createEditorQuestionnaireListSql(EditorQuestionnaireQo req) {
        StringBuffer hsql = new StringBuffer();

        hsql.append("select create_id createId,create_time createTime,dept_id deptId,dept_name deptName,questionnaire_code questionnaireCode,questionnaire_date " +
                "questionnaireDate,questionnaire_flag  questionnaireFlag,questionnaire_id questionnaireId,questionnaire_name questionnaireName,questionnaire_state" +
                " questionnaireState,questionnaire_version questionnaireVersion,questionnaire_type questionnaireType,org_id orgId,org_name orgName,effective_time " +
                "effectiveTime,if_today ifToday,with_title questionnaireWithTitle,if_reuse ifReuse,type,form_title_word_size formTitleWordSize,question_tag_word_size questionTagWordSize,options_word_size optionsWordSize," +
                "hid_title hidTitle,hid_serial_num hidSerialNum,hid_progress_bar hidProgressBar,questionnaire_mould questionnaireMould from editor_questionnaire  where 1=1 ");
        if (CommonUtils.isNotNull(req.getQuestionnaireIdList())) {
            hsql.append(" and  questionnaire_id in(:questionnaireIdList) ");
        }
        if (CommonUtils.isNotNull(req.getQuestionnaireName())) {
            hsql.append(" and  questionnaire_name  like:questionnaireName ");
        }
        if (CommonUtils.isNotNull(req.getQuestionnaireMould())) {
            hsql.append(" and  questionnaire_mould  like:questionnaireMould ");
        }
        if (CommonUtils.isNotNull(req.getQuestionnaireState())) {
            hsql.append(" and  questionnaire_state  =:questionnaireState ");
        }
        hsql.append(" and delete_flag is null ");
        hsql.append("  order by  create_time desc ");
        return hsql.toString();
    }

    @DAOMethod(sql = "update EditorQuestionnaire set questionnaireState=:questionnaireState where questionnaireId =:questionnaireId ")
    public abstract void updateEditorQuestionnaireState(@DAOParam("questionnaireId") String questionnaireId, @DAOParam("questionnaireState") Byte questionnaireState);

    @DAOMethod(sql = "from EditorQuestionnaire where questionnaireCode  =:questionnaireCode order by createTime ")
    public abstract List<EditorQuestionnaire> queryEditorQuestionnaireListByCode(@DAOParam("questionnaireCode") String questionnaireCode);


    public Long queryEditorQuestionnaireCount(final EditorQuestionnaireQo req) {
        HibernateStatelessResultAction<Long> action = new AbstractHibernateStatelessResultAction<Long>() {
            @Override
            public void execute(StatelessSession ss) {
                StringBuilder sqlBuilder = new StringBuilder();
                sqlBuilder.append("select count(1) countValue from editor_questionnaire a where 1=1 ");
                if (CommonUtils.isNotNull(req.getQuestionnaireName())) {
                    sqlBuilder.append(" and  questionnaire_name  like  '%" + req.getQuestionnaireName() + "%'");
                }
                if (CommonUtils.isNotNull(req.getQuestionnaireMould())) {
                    sqlBuilder.append(" and  questionnaire_mould  =  '" + req.getQuestionnaireMould() + "'");
                }
                if (CommonUtils.isNotNull(req.getQuestionnaireState())) {
                    sqlBuilder.append(" and  questionnaire_state  =  '" + req.getQuestionnaireState() + "'");
                }
                if (CommonUtils.isNotNull(req.getQuestionnaireIdList())) {
                    sqlBuilder.append(" and  questionnaire_id  in  :questionnaireIdList");

                }
                sqlBuilder.append(" and delete_flag is null ");
                sqlBuilder.append("  order by  create_time desc ");
                Query query = ss.createSQLQuery(sqlBuilder.toString());
                if (CommonUtils.isNotNull(req.getQuestionnaireIdList())) {
                    query.setParameterList("questionnaireIdList", req.getQuestionnaireIdList());
                }

                query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);

                List<Map> dbList = query.list();

                if (CommonUtils.isNotEmpty(dbList)) {
                    setResult(Long.valueOf(String.valueOf(dbList.get(0).get("countValue"))));
                } else {
                    setResult(0L);
                }
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }


    public List<String> queryEditorQid(final EditorQuestionnaireQo req) {
        HibernateStatelessResultAction<List<String>> action = new AbstractHibernateStatelessResultAction<List<String>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                StringBuffer hsql = new StringBuffer();

                hsql.append("select a.questionnaire_id\n" +

                        " from editor_authority a where ");


                hsql.append("authority_org=:authorityOrg and authority_dept=:authorityDept");

                SQLQuery sqlQuery = ss.createSQLQuery(hsql.toString());
                sqlQuery = (SQLQuery) sqlQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
                sqlQuery.setParameter("authorityOrg", req.getOrgId());
                sqlQuery.setParameter("authorityDept", req.getDeptId());


                List<Map> lsm = (List<Map>) sqlQuery.list();
                List<String> list = new ArrayList<>();
                if (null != lsm && lsm.size() > 0) {
                    for (Map map : lsm) {
                        list.add((String) map.get("questionnaire_id"));
                    }
                }
                setResult(list);

            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }


    public List<String> queryEditorByorgId(final EditorQuestionnaireQo req) {
        HibernateStatelessResultAction<List<String>> action = new AbstractHibernateStatelessResultAction<List<String>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                StringBuffer hsql = new StringBuffer();

                hsql.append("select  a.questionnaire_id\n" +
                        " from editor_authority a where 1=1 and status ='1' ");
                if (CommonUtils.isNotEmpty(req.getOrgList())){
                    hsql.append("  and authority_org in:authorityOrg ");
                }
                if (StringUtils.isNotEmpty(req.getLoginUserId())){
                    hsql.append(" and authority_user=:authorityUser ");
                }
                if (StringUtils.isNotEmpty(req.getOrgId())){
                    hsql.append("  and authority_org =:orgId ");
                }
                if (StringUtils.isNotEmpty(req.getDeptId())){
                    hsql.append(" and authority_dept =:deptId ");
                }
                SQLQuery sqlQuery = ss.createSQLQuery(hsql.toString());
                sqlQuery = (SQLQuery) sqlQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
                if (CommonUtils.isNotEmpty(req.getOrgList())) {
                    sqlQuery.setParameterList("authorityOrg", req.getOrgList());
                }
                if (CommonUtils.isNotEmpty(req.getLoginUserId())) {
                    sqlQuery.setParameter("authorityUser", req.getLoginUserId());
                }
                if (StringUtils.isNotEmpty(req.getOrgId())){
                  sqlQuery.setParameter("orgId",req.getOrgId());
                }
                if (StringUtils.isNotEmpty(req.getDeptId())){
                    sqlQuery.setParameter("deptId",req.getDeptId());
                }
                List<Map> lsm = (List<Map>) sqlQuery.list();
                List<String> list = new ArrayList<>();
                if (null != lsm && lsm.size() > 0) {
                    for (Map map : lsm) {
                        list.add((String) map.get("questionnaire_id"));
                    }
                }
                setResult(list);

            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }


}